<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once("Core.php");
define('TOKEN',   'sztiaopi');
define('SIGNKEY', '168zghtcom168zghtcom168zghtcomht');



class CI_Wechat extends CI_Core{
	private $wechatApi;
	function __construct(){
		parent::__construct();
		$this->database('default');
		$this->ci->load->library('Huashang/user');
		$this->wechatApi = new WechatAPI();
	}
	public function api_templateMessage($openid,$tempId,$msg,$url=''){
		return $this->templateMessage($openid,$tempId,$msg,$url);
	}
	public function api_loginQR($pc=false){
		return $this->wechatApi->loginQR($pc);
	}
	public function api_getAddrSign($arr){
		return $this->wechatApi->getAddrSign($arr);
	}
	public function api_getSDKSign($url){
		return $this->wechatApi->getSDKSign($url);
	}
	public function api_getBasicInfo($openid){
		return $this->wechatApi->getUserInfo($openid);
	}
	public function api_getUnifiedorderSign($arr){
		return $this->wechatApi->getUnifiedorderSign($arr);
	}
	public function api_getOrderQuery($sn,$type='order'){
		return $this->wechatApi->getOrderQuery($sn,$type);
	}
	public function api_send_custom_message($msg){
		return $this->wechatApi->message($msg);
	}
	public function resetConnect($id){
		$this->db->update('site',array('is_validate'=>1),array('id'=>$id));
	}
	//微信入口
	public function api_init(){
		$this->wechatApi->init();
	}
	//获取随机微信账号
	public function getActiveSite(){
		$rs = $this->get_one('*',array('status'=>1),'site');
		return $this->status(true, $rs);
	}
	//获取默认微信商户账号
	public function getDefaultMerchant(){
		$rs = $this->get_one('*',array('default_merchant'=>2),'site');
		if($rs==array()){
			$rs = $this->get_one('*',array(),'site');
		}
		return $this->status(true, $rs);
	}
	//获取所有微信账号
	public function getAllSites(){
		$rs = $this->get_all('*',array(),'site');
		return $this->status(true, $rs);
	}
	//更新微信菜单
	public function menu(){
		$id=$this->ci->session->userdata('wechat_id')?$this->ci->session->userdata('wechat_id'):$this->ci->input->post('wechat_id');
		$arr = $this->get_one('wechat_menu',array('id'=>$id),'site');
		$menu=json_decode($arr['wechat_menu'],true);
		return $this->status(true, $menu);
	}
	public function savemenu($site_id){
		$data['wechat_menu'] = $this->ci->input->post('data');
		$_POST['id']=$site_id;
		$this->write($data,'site');
		$arr = $this->get_one('sn',array('id'=>$site_id),'site');
		$_GET['sn']=$arr['sn'];
		$data['wechat_menu']=str_replace('_S1_','view',$data['wechat_menu']);
		$data['wechat_menu']=str_replace('_S2_','click',$data['wechat_menu']);
		$data['wechat_menu']=str_replace('_S3_','view',$data['wechat_menu']);
		$data['wechat_menu']=str_replace('_S4_','click',$data['wechat_menu']);
		$this->wechatApi->buildMenu($data['wechat_menu']);
	}
	//更新菜单模块
	public function module(){
		$arr=$this->get_all('*',array('parent_id'=>'0'),'article_category');
		foreach($arr as $v){
			$guest[] = array(
				'id'  => $v['id'],
				'name'=> $v['name'],
				'tag' => $v['id'],
				'type'=> $v['list_type'],
				'key' => 'MYKEY'.$v['id'],
				'en_name'=>$v['en_name'],
				'external_url'=>$v['external_url']
			);
		}
		return $this->status(true, $guest);
	}
	//获取微信用户基本信息
	public function user_info($id=''){
		$id=$id?$id:$this->ci->session->userdata('wechat_id');
		$rs=$this->get_one('*',array('id'=>$id),'site');
		return $this->status(true, $rs);
	}
	//获取微信站点列表
	public function getlist(){
		$this->open('site');
		$data=$this->get_list(array(),array());
		foreach($data['result'] as $v){
			$arr[]=array('id'=>$v['id'],'is_validate'=>$v['is_validate'],'status'=>$v['status'],'name'=>$v['name'],'wechat_id'=>$v['wechat_id'],'wechat_oid'=>$v['wechat_oid'],'app_id'=>$v['app_id'],'sn'=>$v['sn']);
		}
		ob_clean();
		$rs = array('total'=>$data['total_rows'],'rows'=>$arr);
	    return $this->status(true,$rs);
	}
	//删除微信
	public function remove(){
		$this->db->where_in('id', explode(',',$this->ci->input->post('id')));
		$this->db->delete('site');
	}
	//更新微信
	public function update(){
		$rs = $this->edit('site');
		return $this->status(true, $rs);
	}
	public function getById($id){
		$rs = $this->get_one('*',array('id'=>$id),'site');
		return $this->status(true, $rs);
	}
	public function getBysn($sn){
		$rs = $this->get_one('*',array('sn'=>$sn),'site');
		return $this->status(true, $rs);
	}
	//保存微信
	public function save(){
		$arr = $this->get_all('id',array(),'site');
		if(count($arr)>=5){
			exit('{"status":"ERROR","msg":"已超过最大站点数量!"}');
		}
		$row['name']       = $this->ci->input->post('name');
		$row['wechat_id']  = $this->ci->input->post('wechat_id');
		$row['wechat_oid'] = $this->ci->input->post('wechat_oid');
		$row['app_id']     = $this->ci->input->post('app_id');
		$row['app_key']    = $this->ci->input->post('app_key');
		$row['address']    = $this->ci->input->post('address');
		$row['geo_lat']    = $this->ci->input->post('geo_lat');
		$row['geo_lng']    = $this->ci->input->post('geo_lng');
		$row['phone']      = $this->ci->input->post('phone');
		$row['merchant_id']= $this->ci->input->post('merchant_id');
		$row['qr']         = $this->ci->input->post('qr');
		$row['qr_text']    = $this->ci->input->post('qr_text');
		if($this->ci->input->post('status')) $row['status']     = $this->ci->input->post('status');
		$row['default_merchant'] = $this->ci->input->post('default_merchant');
		if(!$this->ci->input->post('id')){
			$row['sn']=uniqid();
			$a=$this->get_one('id',array('wechat_id'=>$row['wechat_id']),'site');
			if($a!=array()) exit('{"status":"ERROR","msg":"微信号已存在!"}');
		}
		if($row['default_merchant']){
			$this->db->update('site',array('default_merchant'=>1));
		}
		$this->write($row,'site');
	}
	//获取粉丝
	public function getFans($arr=array(),$tjarr=array()){
		$this->open('wechat_fans');
		$data=$this->get_list($arr,$tjarr);
		ob_clean();
		$rs = array('total'=>$data['total_rows'],'rows'=>$data['result']);
	    return $this->status(true,$rs);
	}
	/*******************客服************************/
	//获取列表
	public function getservice($arr=array(),$tjarr=array()){
		$this->open('service');
		$data=$this->get_list($arr,$tjarr);
		ob_clean();
		$rs = array('total'=>$data['total_rows'],'rows'=>$data['result']);
	    return $this->status(true,$rs);
	}
	public function getServiceById($id){
		$rs = $this->get_one('*',array('id'=>$id),'service');
		return $this->status(true, $rs);
	}
	public function saveService($rs,$sn){
		$rs['add_time']=time();
		$rs['site_sn']=$sn;
		$_GET['sn']=$sn;
		$b=$this->get_one('wechat_id', array('sn'=>$sn),'site');
		$a=$this->get_one('password', array('id'=>$rs['admin_id']),'admin');
		
		$this->write($rs,'service');
		if($rs['id']){
			$this->wechatApi->operatorUpdate(array('id'=>$rs['id'].'@'.$b['wechat_id'],'name'=>$rs['nick'],'password'=>$a['password']));
			$this->wechatApi->operatorHeadImg($rs['id'].'@'.$b['wechat_id'],$rs['image']);
		}else{
			$this->wechatApi->operatorAdd(array('id'=>$this->db->insert_id().'@'.$b['wechat_id'],'name'=>$rs['nick'],'password'=>$a['password']));
			$this->wechatApi->operatorHeadImg($this->db->insert_id().'@'.$b['wechat_id'],$rs['image']);
		}
	}
	//删除客服
	public function delService($sn){
		$_GET['sn']=$sn;
		$b=$this->get_one('wechat_id', array('sn'=>$sn),'site');
		$ids=explode(',',$this->ci->input->post('id'));
		foreach($ids as $v){
			$this->wechatApi->operatorDelete($v.'@'.$b['wechat_id']);
		}
		$this->db->where_in('id', explode(',',$this->ci->input->post('id')));
		$this->db->delete('service');
	}
	/************END客服************************/
	//推送列表
	public function getpush($type){
		$this->open('push_news');
		$data=$this->get_list(array('msg_type'=>"value:$type",'wechat_id'=>'value:'.$this->ci->session->userdata('wechat_id')),array());
		ob_clean();
		$rs = array('total'=>$data['total_rows'],'rows'=>$data['result']);
		return $this->status(true, $rs);
	}
	/**********保存推送消息**********/
	public function savePush($data){
		$data['add_time']=time();
		$this->write($data,'push_news');
	}
	//查看当月推送条数
	public function monthnum(){
		$BeginDate=strtotime(date('Y-m-01', strtotime(date("Y-m-d"))));
	    $Lastdate= strtotime(date('Y-m-d', strtotime("$BeginDate +1 month -1 day")));
		$sql = "select count(id) as total from ht_push_news where add_time >=$BeginDate and add_time <=$Lastdate and wechat_id='".$this->ci->session->userdata('wechat_id')."'";
		$query = $this->db->query($sql);
		$arr = $query->result_array($sql);
		return $this->status(true, $arr);
	}
	//发送头条新闻推送
	public function broadcastPush($ids,$task,$wechat_id,$type){
		$site=$this->get_one('sn',array('id'=>$wechat_id),'site');
		$_GET['sn']=$site['sn'];
		$rows = $this->get_all('*',array(),'article',array('wherein'=>array('id'=>explode(',',$ids))));
		$this->db->update('push_news',array('status'=>2),array('id'=>$task));
		if($type=='batch'){
			$this->wechatApi->groupMessage($rows,$task);
		}else{
			$data=array();
			foreach($rows as $v){
				$data[]=array(
					'title'  => $v['title'],
					'pic'    => array_shift(json_decode($v['thumb'],true)),
					'url'    => str_replace('/admin/','/wechat/',WEB).$v['en_title'].'_1.html',
					'content'=>$v['remark'],
					'wechat_urls' => json_decode($v['wechat_urls'],true),
					'direct' => $v['direct']
				);
			}
			$users = $this->get_all('openid',array('source'=>'WECHAT'),'user');
			foreach($users as $v){
				$this->wechatApi->message(array('openid'=>$v['openid'],'data'=>$data),$op);
			}
		}
	}
	//获取推送新闻
	public function getPushNews($ids){
		$rs = $this->get_all('*',array(),'article',array('wherein'=>array('id'=>explode(',',$ids))));
		return $this->status(true, $rs);
	}
	//获取所有微信列表
	function alllist(){
		$rs = $this->get_all('*',array(),'site');
		return $this->status(true,$rs);
	}
	//切换微信
	public function change_wechat(){
		$a=$this->get_one('id,name,sn',array('id'=>$this->ci->input->post('id')),'site');
		if($a==array()) return $this->status('ERROR','');
		$this->db->update('admin',array('active_site'=>$a['id']),array('id'=>$this->ci->session->userdata('admin_id')));
		$this->ci->session->set_userdata('wechat_id',$a['id']);
		$this->ci->session->set_userdata('wechat_name',$a['name']);
		$this->ci->session->set_userdata('sn',$a['sn']);
		return $this->status('OK','');
	}
	//设置微信欢迎词
	public function welcome($id,$site_id){
		if(!$id || !$site_id) return $this->status(false);
		$arr = $this->get_one('id',array('welcome_site'=>$site_id),'article');
		if($arr!=array()) $this->db->update('article',array('welcome_site'=>''),array('id'=>$arr['id']));
		$this->db->update('article',array('welcome_site'=>$site_id),array('id'=>$id));
	}
	public function get_welcome($site_id){
		$arr = $this->get_one('*',array('welcome_site'=>$site_id),'article');
		$arr['intro']=strip_tags($arr['content']);
		$arr['thumb']=array_shift(json_decode($arr['thumb'],true));
		return $this->status(true,$arr);
	}
	//自动回复列表
	public function getwords($arr=array(),$tj_arr=array()){
		$this->open('reply_words');
		$data=$this->get_list($arr,$tj_arr);
		ob_clean();
		$rs = array('total'=>$data['total_rows'],'rows'=>$data['result']);
	   return $this->status(true, $rs);
	}
	//修改自动回复
	public function editwords($id){
		$id=$id?$id:$this->ci->input->get('id');
		$rs=$this->get_one('*',array('id'=>$id),'reply_words');
		return $this->status(true, $rs);
	}
	//保存自动回复
	public function savewords(){
		$arr = $_POST;
		$arr['content']=strip_tags($arr['content'],'<a>,<b>,<br>');
		$arr['site_id']=$this->ci->session->userdata('wechat_id');
		$arr['user_id']=$this->ci->session->userdata('admin_id');
		if($arr['is_default']==2) $this->db->update('reply_words',array('is_default'=>1),array());
		$this->write($arr,'reply_words');
	}
	//删除自动回复
	public function delwords(){
		$this->db->where_in('id', explode(',',$this->ci->input->post('id')));
		$this->db->delete('reply_words');
	}
	///***********微信 文章模板************/
	public function template_channel(){
		$arr = $this->get_one('wechat_menu',array('id'=>$this->ci->session->userdata('wechat_id')),'site');
		$menu=json_decode($arr['wechat_menu'],true);
		return $this->status(true, $menu);
	}
	
	//微信文章详情
	public function template_detail(){
		$arr = $this->get_one('wechat_menu',array('id'=>$this->ci->session->userdata('wechat_id')),'site');
		$menu=json_decode($arr['wechat_menu'],true);
		return $this->status(true, $menu);
	}
	//保存微信文章详情
	public function savetemplate(){
		$arr = $_POST;
		$arr['site_id']=$this->ci->session->userdata('wechat_id');
		$arr['user_id']=$this->ci->session->userdata('admin_id');
		$row = $this->get_one('id',array('site_id'=>$arr['site_id'],'channel_id'=>$arr['channel_id']),'template');
		if($row==array()) $this->db->insert('template',$arr);
		else $this->db->update('template',$arr,array('id'=>$row['id']));
	}
	public function get_template($id){
		$id=$id?$id:$this->ci->input->get('id');
		$arr=$this->get_one('*',array('channel_id'=>$id),'template');
		return $this->status(true, $arr);
	}
	//根据回复关键字查找信息
	public function sendInfo($info){
		$rs=$this->get_all('words,content,is_default,reply_type',array('site_id'=>$this->ci->session->userdata('site_id')),'reply_words');
		foreach($rs as $v){
			if($v['is_default']==2) $default=$v;
			$a=explode(',', $v['words']);
			if(in_array(trim($info), $a)){
				if($v['reply_type']==1){
					$a=array_shift(json_decode($v['content'],true));
					$this->wechatApi->printText(($a['link']?"<a href=\"$a[link]\">":"").$a[text].($a['link']?"</a>":""));
					return;
				}else{
					$b=json_decode($v['content'],true);
					foreach($b as $t){
						$data[]=array(
							'title'=>$t['text'],
							'pic'  =>IMGURL.$t['image'].'?time='.time(),
							'url'  => $t['link'],
						);
					$this->wechatApi->printTextPic($data);
					return;
				}
				}
			}
		} 
		//if(!$default) $default=array_pop($rs);
		if($default['reply_type']==1){
			$a=array_shift(json_decode($default['content'],true));
			$this->wechatApi->printText(($a['link']?"<a href=\"$a[link]\">":"").$a[text].($a['link']?"</a>":"")); 
			return ;
		}else{
			$b=json_decode($default['content'],true);
			foreach($b as $t){
				$data[]=array(
					'title'=>$t['text'],
					'pic'  =>IMGURL.$t['image'].'?time='.time(),
					'url'  => $t['link'],
				);
			}
			$this->wechatApi->printTextPic($data);
			return ;
		}
	}
	/*** 保存新闻到微信服务器 ***/
	public function saveNewsToWechat($id,$arr,$sns){
		if(!$arr['thumb'] || !$id) return false;
		$news  = $this->get_one('wechat_urls,direct',array('id'=>$id),'article');
		if($news['direct']) return false; 
		$sites = $this->get_all('*',array(),'site',array('wherein'=>array('id'=>$sns)));
		$urls  = json_decode($news['wechat_urls'],true);
		foreach($sites as $v){
			$_GET['sn']=$v['sn'];
			$s = $this->wechatApi->saveArticle($arr);
			if($s) $urls[$v['sn']] = $s;
		}
		$this->db->update('article',array('wechat_urls'=>json_encode($urls)),array('id'=>$id));
	}
	/**保存发送消息*/
	public function savemessage(){
		$arr = $_POST;
		unset($arr['editorValue']);
		$a=str_replace('target=\"_self\"','',strip_tags($arr['reply_text'],'<a>'));
		$a=str_replace('=\"', "='", $a);
		$a=str_replace('\"', "'", $a);
		$arr['reply_text']=$a;
		$arr['reply_time']=time();
		$arr['reply_status']=2;
		$this->write($arr,'message');
	}
}

/*** 微信封装类 V2.0版本 ****/
class WechatAPI extends CI_Core{
	private $token;
	private $fromUser;
	private $toUser;
	private $appId;
	private $appSecret;
	private $site_name;
	private $site_url;
	private $site_id;
	function __construct(){
		parent::__construct();
		$this->database('default');
		$this->ci->load->library('Huashang/user');
	}
	public function init(){
		$this->getSite();
		$this->receive();
	}
	private function getSite(){
		$site = $this->get_one('*',array('sn'=>$this->ci->input->get('sn')),'site');
		
		if($site==array()) exit('Account is not existed!');
		$this->appId     = $site['app_id'];
		$this->appSecret = $site['app_key'];
		$this->site_name = $site['name'];
		$this->site_id   = $site['id'];
		//if($site['is_validate']==2){
			
			$echoStr = $_GET["echostr"];
			if($echoStr && $this->checkSignature()){ file_put_contents('ccc.txt',$echoStr);
				ob_clean();
				echo $echoStr;
				//$this->db->update('site',array('is_validate'=>1),array('id'=>$site['id']));
				exit;
			}
		//}
	}
	/*** 检查审核通过 ***/
	private function checkSignature(){
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
		file_put_contents('aaaaaaaaa.txt',$tmpStr."---".$signature);
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
	/*** 获取微信ACCESS TOKEN ***/
	public function getAuth(){
		$this->getSite(); 
		$f='../uploads/file/access_token.json';
		$data = json_decode(file_get_contents($f));
		if($data->expire_time < time()){
			$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appId."&secret=".$this->appSecret;
			$res = json_decode($this->curl_get($url));
			if($res->errcode==40001 && file_exists($f)) unlink($f);
			$access_token = $res->access_token;
			if($access_token){
				$data->expire_time = time() + 7200;
				$data->access_token = $access_token;
				file_put_contents($f,json_encode($data));
			}
		}else{
			$access_token = $data->access_token;
		}
		$this->token = $access_token;
		return $access_token;
	}
	/*** 创建菜单 ***/
	public function buildMenu($data){
		$this->getAuth();
		$MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$this->token;
		$content = $this->curl_post($MENU_URL,$data);
		echo $content;
	}
	/*** 添加客服 ***/
	public function operatorAdd($user){
		$this->getAuth();
		$url =  'https://api.weixin.qq.com/customservice/kfaccount/add?access_token='.$this->token;
		$data= '{"kf_account":"'.'op'.$user['id'].'","nickname":"'.$user['name'].'","password":"'.$user['password'].'"}';
		$content = $this->curl_post($url,$data);
	}
	/*** 更新客服 ***/
	public function operatorUpdate($user){
		$this->getAuth();
		$url =  'https://api.weixin.qq.com/customservice/kfaccount/update?access_token='.$this->token;
		$data= '{"kf_account":"'.'op'.$user['id'].'","nickname":"'.$user['name'].'","password":"'.$user['password'].'"}';
		$content = $this->curl_post($url,$data);
	}
	/*** 删除客服 ***/
	public function operatorDelete($userid){
		$this->getAuth();
		$url =  'https://api.weixin.qq.com/customservice/kfaccount/del?access_token='.$this->token.'&kf_account='.'op'.$userid;
		$content = $this->curl_get($url);
	}
	/*** 保存客服头像 ***/
	public function operatorHeadImg($user,$img){
		$this->getAuth();
		$upload_url =  'https://api.weixin.qq.com/customservice/kfaccount/uploadheadimg?access_token='.$this->token.'&kf_account='.'op'.$user;
		$media = realpath('../'.$img);
		$post = array('kf_account'=>'op'.$user,'media'=>'@'.$media);
		$this->uploadBinary($upload_url,$post);
	}
	/*** 打印文本消息 ***/
	public function printText($content,$flag = 0){
		$tpl = "<xml> 
				<ToUserName><![CDATA[".$this->fromUser."]]></ToUserName> 
				<FromUserName><![CDATA[".$this->toUser."]]></FromUserName> 
				<CreateTime>".$_SERVER['REQUEST_TIME']."</CreateTime> 
				<MsgType><![CDATA[text]]></MsgType> 
				<Content><![CDATA[".$content."]]></Content> 
				<FuncFlag>".$flag."</FuncFlag>
				</xml>";
		ob_clean();
		echo $tpl;
	}
	/*** 打印图文消息 ***/
	public function printTextPic($data,$flag = 0){
		foreach($data as $v){
			$arr[] = "<item><Title><![CDATA[$v[title]]]></Title><Description><![CDATA[$v[intro]]]></Description><PicUrl><![CDATA[$v[pic]]]></PicUrl><Url><![CDATA[$v[url]]]></Url></item>";
		}
		$tpl = " <xml>
			 <ToUserName><![CDATA[".$this->fromUser."]]></ToUserName>
			 <FromUserName><![CDATA[".$this->toUser."]]></FromUserName>
			 <CreateTime>".$_SERVER['REQUEST_TIME']."</CreateTime> 
			 <MsgType><![CDATA[news]]></MsgType> 
			 <Content><![CDATA[%s]]></Content> 
			 <ArticleCount>".count($arr)."</ArticleCount> 
			 <Articles>".implode('',$arr)."</Articles> 
			 <FuncFlag>".$flag."</FuncFlag> 
			 </xml> ";
		ob_clean();
		echo $tpl;
	}
	private function parseURL($content){
		preg_match_all('/href="(.*?)"/is',$content,$arr); 
		foreach($arr[1] as $v){
			$content = str_replace($v,$v.(stristr($v,'?')?'&':'?').'sn='.$_GET['sn'],$content);
		}
		return $content;
	}
	/*** 保存文章到微信 ***/
	public function saveArticle($arr){
		$this->getAuth();
		$media_id = $this->uploadMedia('thumb','../'.$arr['thumb']);
		$url='https://api.weixin.qq.com/cgi-bin/material/add_news?access_token='.$this->token;
		$data = array(
			'articles'=>array(array(
				'title'=>$arr['title'],
				'thumb_media_id'=>$media_id,
				'author'=>'',
				'digest'=>$arr['intro'],
				'show_cover_pic'=>0,
				'content'=>$this->parseURL($arr['content'])
			))
		);
		$content = json_decode($this->curl_post($url,json_encode($data,JSON_UNESCAPED_UNICODE)),true);
		
		$media_id = $content['media_id']; 
		$url = 'https://api.weixin.qq.com/cgi-bin/material/get_material?access_token='.$this->token;
		$rs = json_decode($this->curl_post($url,'{"media_id":"'.$media_id.'"}'),true);
		
		return $rs['news_item'][0]['url'];
	}
	/*** 上传微信素材 ***/
	public function uploadMedia($type,$file){
		$upload_url = 'https://api.weixin.qq.com/cgi-bin/material/add_material?type='.$type.'&access_token='.$this->token;
		$media = realpath($file);
		$post = array('media'=>'@'.$media);
		$arr = json_decode($this->uploadBinary($upload_url,$post),true);
		return $arr['media_id'];
	}
	private function uploadBinary($url,$post){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_POST,1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$result=curl_exec($ch);
		curl_close($ch);
		return $result;
	}
	/*** 发送单条信息 ***/
	public function message($msg,$op){
		$extra = '';
		$b=$this->get_one('wechat_id,sn', array('sn'=>$_GET['sn']),'site');
		$this->getAuth();
		$url =  'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$this->token;
		if($op) $extra = '"customservice":{"kf_account":"'.'op'.$op.'@'.$b['wechat_id'].'"},';
		if($msg['data']){
			foreach($msg['data'] as $v){
				$arr[]='{"title":"'.$v['title'].'","description":"'.strip_tags($v['content']).'","url":"'.($v['direct']?$v['direct']:($v['wechat_urls'][$b['sn']]?$v['wechat_urls'][$b['sn']]:$v['url']."?sn=".$_GET['sn'])).'","picurl":"'.IMGURL.$v['pic'].'?time='.time().'"}';
			}
			$data = '{'.$extra.'"touser":"'.$msg['openid'].'","msgtype":"news","news":{"articles": ['.implode(',',$arr).']}}';
		}else{
			$data = '{'.$extra.'"touser":"'.$msg['openid'].'","msgtype":"text","text":{"content":"'.strip_tags($msg['content'],'<a>').'"}}';
		}
		$content = $this->curl_post($url,$data);
		echo $content;
	}
	/*** 群发消息 ***/
	public function groupMessage($rows,$id){
		$this->getAuth();
		foreach($rows as $v){
			$media_id = $this->uploadMedia('thumb','../'.array_shift(json_decode($v['thumb'],true)));
			$data['articles'][]=array('thumb_media_id'=>$media_id,'title'=>$v['title'],'content'=>$v['content'],'show_cover_pic'=>0);
		}
		$news_url = 'https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token='.$this->token;
		$content = $this->curl_post($news_url, json_encode($data,JSON_UNESCAPED_UNICODE));
		$arr = json_decode($content,true);
		$data = array(
			'filter'=>array('is_to_all'=>true),
			'mpnews'=>array('media_id'=>$arr['media_id']),
			'msgtype'=>'mpnews'
		);
		$url = 'https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token='.$this->token;
		$content = $this->curl_post($url,json_encode($data));
		echo $content;
		$arr = json_decode($content,true);
		$this->db->update('push_news',array('wechat_msg_id'=>$arr['msg_id']),array('id'=>$id));
	}
	/*** 模板消息 ***/
	public function templateMessage($openid,$MP,$msg,$clickUrl=''){
		$this->getAuth();
		$url = 'https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token='.$this->token;
		$this->curl_post($url,json_encode(array('industry_id1'=>'1','industry_id2'=>'2')));
		$url = 'https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token='.$this->token;
		$arr = json_decode($this->curl_post($url,json_encode(array('template_id_short'=>$MP))),true);
		$url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$this->token;
		$data= array(
			'touser'=>$openid,
			'url'=>$clickUrl,
			'template_id'=>$arr['template_id'],
			'data'=>$msg
		);
		$content = $this->curl_post($url,json_encode($data,JSON_UNESCAPED_UNICODE));
	}
	/*** 获取粉丝信息 ***/
	public function getUserInfo($openid){
		if(!$openid) return;
		$this->getAuth();
		$url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$this->token.'&openid='.$openid.'&lang=zh_CN';
		$json = $this->curl_get($url);
		file_put_contents('../uploads/accessTokenLog.txt',$json);
		$user = json_decode($json,true);
		$row = array(
			'openid'     => $openid,
			'belong_site'=> $this->site_id,
			'sex'        => $user['sex'],
			'nickname'   => $user['nickname'],
			'headimg'    => $user['headimgurl'],
			'address'    => "$user[country] $user[province] $user[city]",
		);
		$a = $this->get_one('id',array('openid'=>$openid),'user');
		if($a!=array()&&$row['nickname']) $this->db->update('user',$row,array('id'=>$a['id']));
		return $row;
	}
	/*** 记录粉丝操作 ***/
	private function notify($title,$msg,$level=1){
		$fields = array('msg_type'=>'wechat','title'=>$title,'content' =>$msg,'from_user'=>$this->fromUser,'to_user'=>$this->toUser,'msg_level'=>$level);
		$row = array(
			'msg_type'  => $fields['msg_type'],
			'title'     => $fields['title'],
			'content'   => $fields['content'],
			'from_user' => $fields['from_user'],
			'to_user'   => $fields['to_user'],
			'msg_level' => $fields['msg_level'],
			'add_time'  => time()
		);
		$this->db->insert('message',$row);
		$fields['msg_id']=$this->db->insert_id();
		$this->push($fields);
	}
	/*** 点击菜单事件 ***/
	private function trackMenuClick($key,$user){
		$type = array_pop(explode('_', $key));
		$cate = str_replace('MYKEY','',array_shift(explode('_', $key)));
		$ids=array($cate);
		$this->ci->load->library('Huashang/articlecategory');
		$this->ci->articlecategory->getCategory($cate,$ids);
		$arr = $this->get_one('*',array('id'=>$cate),'article_category');
		if($type=='TEXT'){//纯文本
			$rs = $this->get_one('content',array('category_id'=>$arr['id']),'article');
			$this->printText(strip_tags($rs['content'],'<a>'));
		}
		if($type=='TPIC'){//图文
			$rs = $this->get_all('*',array(),'article',array('order'=>'id desc','limit'=>10,'wherein'=>array('category_id'=>$ids)));
			foreach($rs as $v){
				$urls = json_decode($v['wechat_urls'],true);
				$p = array_shift(json_decode($v['thumb'],true));
				$data[]=array(
					'title'=> $v['title'],
					'pic'  => WEB.(stristr($p,'../uploads')?$p:"../$p").'?time='.time(),
					'url'  => $v['direct']?$v['direct']:($urls[$_GET['sn']]?$urls[$_GET['sn']]:str_replace('/admin/','/wechat/',WEB).$v['en_title'].'_1.html?sn='.$_GET['sn']),
					'intro'=> $v['remark'],//trim(str_replace('&nbsp;','',substr(strip_tags($v['content']),0,200)))
				);
			}
			$this->printTextPic($data);
		}
		$this->notify('请求点击', $user.'请求了'.($type=='TPIC'?'微信图文':'微信文本').'：'.$arr['name'],1);
	}
	/*** 根据回复关键字查找信息 ***/
	public function sendInfo($info){
		$rs=$this->get_all('words,content,is_default,reply_type',array('site_id'=>$this->ci->session->userdata('site_id')),'reply_words');
		foreach($rs as $v){
			if($v['is_default']==2) $default=$v;
			$a=explode(',', $v['words']);
			if(in_array(trim($info), $a)){
				if($v['reply_type']==1){
					$a=array_shift(json_decode($v['content'],true));
					$this->printText(($a['link']?"<a href=\"$a[link]\">":"").$a[text].($a['link']?"</a>":""));
					return;
				}else{
					$b=json_decode($v['content'],true);
					foreach($b as $t){
						$data[]=array(
							'title'=>$t['text'],
							'pic'  =>IMGURL.$t['image'].'?time='.time(),
							'url'  => $t['link'],
						);
					$this->printTextPic($data);
					return;
				}
				}
			}
		} 
		//if(!$default) $default=array_pop($rs);
		if($default['reply_type']==1){
			$a=array_shift(json_decode($default['content'],true));
			$this->printText(($a['link']?"<a href=\"$a[link]\">":"").$a[text].($a['link']?"</a>":"")); 
			return ;
		}else{
			$b=json_decode($default['content'],true);
			foreach($b as $t){
				$data[]=array(
					'title'=>$t['text'],
					'pic'  =>IMGURL.$t['image'].'?time='.time(),
					'url'  => $t['link'],
				);
			}
			$this->printTextPic($data);
			return ;
		}
	}
	/*** 获取欢迎词 ***/
	public function getWelcome($site_id){
		$arr = $this->get_one('*',array('welcome_site'=>$site_id),'article');
		$arr['intro']=strip_tags($arr['content']);
		$arr['thumb']=array_shift(json_decode($arr['thumb'],true));
		return $this->status(true,$arr);
	}
	/*** 接收处理 ***/
	private function receive(){
		$postStr        = file_get_contents("php://input");
		$postObj        = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
		$this->fromUser = (string)$postObj->FromUserName;
		$this->toUser   = (string)$postObj->ToUserName; 
		$MsgType        = (string)$postObj->MsgType; 
		$content        = trim($postObj->Content);
		$userInfo       = $this->getUserInfo($this->fromUser);
		if($MsgType == 'text'){//收到消息
			$this->notify('发送微信消息',$userInfo['nickname'].'发送了消息：'.$content,2);
			$this->sendInfo($content);
		}else if($MsgType == 'event'){//推送事件
			$event = $postObj->Event; 
			$eventKey = $postObj->EventKey;
			if($event=='CLICK'){//点击
				$this->trackMenuClick($eventKey,$userInfo['nickname']);
			}else if($event=='VIEW'){//网页
				$this->notify('请求网页', $userInfo['nickname'].'请求了网页：'.$eventKey,1);
			}else if($event=='subscribe'){//订阅
				if(stristr($eventKey,'QR_')) $this->scanLogin($userInfo, (string)$postObj->Ticket, str_replace('qrscene_','',$eventKey));
				$this->subscribe($this->fromUser,$userInfo);
			}else if($event=='unsubscribe'){//取消订阅
				$this->unsubscribe();
			}else if($event=='SCAN'){//扫描事件
				if(stristr($eventKey,'QR_')) $this->scanLogin($userInfo, (string)$postObj->Ticket, $eventKey);
			}
		}
	}
	/*** 扫描登录 ***/
	private function scanLogin($row, $ticket, $eventKey){
		$code = str_replace('QR_','',$eventKey);
		$this->ci->load->library('Huashang/system');
		$oldTicket = file_get_contents("../uploads/file/scan_$code.txt");
		$userInfo  = array_pop($this->ci->user->getByOpendId($this->fromUser));
		if($userInfo == array()){
			$row['source']      = 'WECHAT';
			$row['username']    = 'WX'.sprintf("%u",crc32(uniqid()));
			$row['password']    = md5($this->fromUser);
			$row['scan_ticket'] = $ticket==$oldTicket?$ticket:'';
			$rs = $this->ci->user->create($row);
		}else{
			$row['id']          = $userInfo['id'];
			$row['scan_ticket'] = $ticket==$oldTicket?$ticket:'';
			$this->ci->user->saveRow($row);
		}
	}
	/*** 取消订阅微信号 ***/
	private function unsubscribe(){
		$this->db->update('user',array('is_subscribe'=>2),array('openid'=>$this->fromUser));
		$rs = $this->get_one('*',array('openid'=>$this->fromUser),'user');
		$this->notify('取消订阅微信账号', $rs['nickname'].'取消了订阅微信账号: '.$this->site_name,1);
	}
	/*** 订阅微信号 ***/
	private function subscribe($openid,$row){
		$rs = array_pop($this->getWelcome($this->site_id));
		if($rs['thumb']) $this->printTextPic(array(array('title'=>$rs['title'],'intro'=>$rs['intro'],'pic'=>IMGURL.$rs['thumb'], 'url'=>str_replace('/admin/','/wechat/',WEB).$rs['en_title'].'_1.html')));
		else $this->printText($rs['intro']);
		$existUser  = array_pop($this->ci->user->getByOpendId($openid));
		if($existUser == array()){
			$row['source']      = 'WECHAT';
			$row['username']    = 'WX'.sprintf("%u",crc32(uniqid()));
			$row['password']    = md5($this->fromUser);
			$row['is_subscribe']= 1;
			$this->ci->user->create($row);
		}else{
			$row['is_subscribe']= 1;
			$this->db->update('user',$row,array('id'=>$existUser['id']));
		}
		if($existUser['upline_id']>0){
			$parent = array_pop($this->ci->user->update($existUser['upline_id']));
			$this->message(array('openid'=>$parent['openid'],'content'=>($existUser['nickname']?$existUser['nickname']:$existUser['username']).' 已经成为你的下线会员！'));
		}
		$this->notify('订阅微信账号', $existUser['nickname'].'订阅了微信账号: '.$this->site_name,1);
	}
	/*** 获取微信收货地址签名 ***/
	public function getAddrSign($arr){
		$accessToken = $this->ci->session->userdata('JSToken');
		$arr['check'] = $this->curl_get("https://api.weixin.qq.com/sns/auth?access_token=".$accessToken."&openid=".$this->ci->session->userdata('openid'));
		$arr['timeStamp']=strval(time());
		$arr['nonceStr']= $this->createNonceStr();
		$str = "accesstoken=$accessToken&appid=$arr[appId]&noncestr=$arr[nonceStr]&timestamp=$arr[timeStamp]&url=$arr[url]";
		$arr['addrSign'] = SHA1($str);
		return json_encode($arr);
	}
	private function createNonceStr($length = 16) {
		$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		$str = "";
		for($i=0;$i<$length;$i++) $str.=substr($chars,mt_rand(0,strlen($chars)-1),1);
		return $str;
	}
	private function getJsApiTicket() {
		$f='../uploads/file/jsapi_ticket.json';
		$data = json_decode(file_get_contents($f));
		if($data->expire_time < time()) {
			$this->getAuth();
			$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=".$this->token;
			$res = json_decode($this->curl_get($url));
			$ticket = $res->ticket;
			if($ticket){
				$data->expire_time = time() + 7000;
				$data->jsapi_ticket = $ticket;
				file_put_contents($f,json_encode($data));
			}
		} else {
			$ticket = $data->jsapi_ticket;
		}
		return $ticket;
	}
	/*** 获取微信JS-SDK签名 ***/
	public function getSDKSign($url) {
		$this->getSite();
		$jsapiTicket = $this->getJsApiTicket();
		$timestamp = time();
		$nonceStr = $this->createNonceStr();
		$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
		$signature = sha1($string);
		$signPackage = array(
			"appId"     => $this->appId,
			"nonceStr"  => $nonceStr,
			"timestamp" => $timestamp,
			"url"       => $url,
			"signature" => $signature,
			"rawString" => $string
		);
		return $signPackage; 
	}
	/*** 微信统一下单接口 ****/
	public function getUnifiedorderSign($args){//$args['total_fee']=$args['total_fee']*100;
		$a            = $this->get_one('merchant_id,app_key',array('app_id'=>$args['appid']),'site');
		$merchant     = $a['merchant_id'];
		$out_trade_no = $args['sn'];
		$notify_url   = $args['notify_url'];
		$client_ip    = $args['openid']?$_SERVER['REMOTE_ADDR']:$_SERVER['SERVER_ADDR'];
		$paysign      = "appid=$args[appid]&body=$args[body]&mch_id=$merchant"."_nouncestr_"."&notify_url=$notify_url"."_openid_"."&out_trade_no=$out_trade_no"."_productid_&spbill_create_ip=$client_ip&total_fee=$args[total_fee]&trade_type=$args[trade_type]&key=".SIGNKEY;
		if($args['openid']){
			$paysign = str_replace('_openid_',"&openid=$args[openid]",$paysign);
		}else{
			$paysign = str_replace('_openid_','',$paysign);
		}
		if($args['product_id']){
			$paysign = str_replace('_productid_',"&product_id=$args[product_id]",$paysign);
		}else{
			$paysign = str_replace('_productid_','',$paysign);
		}
		if($args['noncestr']){
			$paysign = str_replace('_nouncestr_',"&nonce_str=$args[noncestr]",$paysign);
		}else{
			$str = $paysign."&key=".SIGNKEY;
			$args['noncestr'] = strtoupper(md5($str));
			$paysign = str_replace('_nouncestr_',"&nonce_str=$args[noncestr]",$paysign);
		} //echo $paysign;exit;
		$paysign      = strtoupper(md5($paysign));
		$data = "<xml>".
				  "<appid>$args[appid]</appid>".
				  "<body>$args[body]</body>".
				  "<mch_id>$merchant</mch_id>".
				  "<nonce_str>$args[noncestr]</nonce_str>".
				  "<notify_url>$notify_url</notify_url>".
				  ($args['openid']?"<openid>$args[openid]</openid>":"").
				  "<out_trade_no>$out_trade_no</out_trade_no>".
				  "<spbill_create_ip>$client_ip</spbill_create_ip>".
				  "<total_fee>$args[total_fee]</total_fee>".
				  "<trade_type>$args[trade_type]</trade_type>".
				  "<sign>$paysign</sign>".
				  ($args['product_id']?"<product_id>$args[product_id]</product_id>":"").
				  "</xml>";
		$content = $this->curl_post('https://api.mch.weixin.qq.com/pay/unifiedorder',$data);
		$arr = json_decode(json_encode(simplexml_load_string($content,'SimpleXMLElement', LIBXML_NOCDATA)),true);
		$arr['package'] = "prepay_id=$arr[prepay_id]&sign=$arr[sign]";
		$arr['timestamp'] = time();
		$str = "appId=$args[appid]&nonceStr=$arr[nonce_str]&package=$arr[package]&signType=MD5&timeStamp=$arr[timestamp]&key=".SIGNKEY;
		$arr['mysign'] = strtoupper(md5($str));
		return json_encode($arr);
	}
	/*** 查询微信订单 **/
	public function getOrderQuery($sn,$type='order'){
		if($type=='order'){
			$order = $this->get_one('pay_wechat',array('order_sn'=>$sn),'order');
		}else{
			$order = $this->get_one('pay_wechat',array('order_sn'=>$sn),'user_asset');
		}
		$a         = $this->get_one('merchant_id',array('app_id'=>$order['pay_wechat']),'site');
		$str       = "appid=$order[pay_wechat]&mch_id=$a[merchant_id]&out_trade_no=$sn&key=".SIGNKEY; 
		$nonce_str = strtoupper(md5($str));
		$str       = str_replace('&out_trade_no',"&nonce_str=$nonce_str&out_trade_no",$str);
		$sign      = strtoupper(md5($str));
		$data      = "<xml><appid>$order[pay_wechat]</appid><mch_id>$a[merchant_id]</mch_id><nonce_str>$nonce_str</nonce_str><out_trade_no>$sn</out_trade_no><sign>$sign</sign></xml>";
		$content = $this->curl_post('https://api.mch.weixin.qq.com/pay/orderquery',$data);
		$arr = json_decode(json_encode(simplexml_load_string($content,'SimpleXMLElement', LIBXML_NOCDATA)),true);
		if($arr['trade_state']=='SUCCESS'){//支付成功
			return $this->status(true,$arr);
		}else{
			return $this->status(false,$arr);
		}
	}
	/*** 创建微信登录二维码 ***/
	public function loginQR($pc=false){
		$code = sprintf("%u",crc32(uniqid()));
		$this->ci->session->set_userdata('qrSession',$code);
		$this->getAuth();
		$url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$this->token; 
		$rs = json_decode($this->curl_post($url,'{"expire_seconds":404800,"action_name":"QR_LIMIT_STR_SCENE","action_info":{"scene":{"scene_str":"QR_'.$code.'"}}}'),true);
		file_put_contents(($pc?'':'../')."uploads/file/scan_$code.txt", $rs['ticket']);
		$this->ci->load->library('Huashang/ciqrcode');
		header("Content-Type: image/png");
		ob_clean();
		$this->ci->ciqrcode->generate(array('data'=>$rs['url']));
	}
}
